import React, { useContext, useEffect, useState } from 'react';
import {
    ActivityIndicator,
    Alert,
    DeviceEventEmitter, Dimensions,
    ImageBackground,
    RefreshControl,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
import { Icon, Image, ListItem, Text } from 'react-native-elements';
import LocaleContext from '../libs/locale';
import WalletContext from '../libs/wallet';
import AsyncStorage from '@react-native-async-storage/async-storage';

import susdtlogo from '../assets/susdt.png';
import sETHlogo from '../assets/1.png';
import otherTokenLogo from '../assets/aboutlogo.png';

import {constansts} from "./../libs/constansts";
import { ScrollView } from 'react-native';
import {useFocusEffect} from "@react-navigation/native";
import {getRandomUrl, getTransferCount, getTxInfo, getTxs, getTxs_Ip, SaveMyID} from "../libs/nodes";
import {formartMoney, sleep, timeFormat} from "../libs/helpers";
import scan from "../assets/Assets/scan.png";
import {bytes2Hex, hex2Bytes, hex2Bytes_Random, keyPairFromSeed} from "../libs/keyPair";
import {convertKeyPair, convertPublicKey} from "../libs/ed2curve";
import Cp from "crypto-js";
import {TouchableHighlight} from "react-native-gesture-handler";


const {width,height,scale} = Dimensions.get("window");


const ChatListTemp = ({navigation,route}:any) =>{
    const locale:any = useContext(LocaleContext);
    const wallet: any = useContext(WalletContext);
    const [ChatList,setChatList]:any = useState([]);
    const [showWaiting,setShowWaiting] = useState(false)
    const [progressLength,setProgressLength] = useState("0")
    const [TipInfo,setTipInfo] = useState("")

    //获取存储的数据并写入列表
    const getStore = async () => {
        // await AsyncStorage.setItem("@chatList","[]") ;
        let SaveList = await AsyncStorage.getItem("@chatList") || "[]";
        // console.log("主页数据："+SaveList)
        var resList: any = JSON.parse(SaveList) || [];
        setChatList(resList);
        return resList;
    }

    //获取最近60笔交易
    // const getRecentTran = async () => {
    //     var info: any = [];
    //     //获取60笔交易的信息
    //     for (let i = 0; i < 10; i++) {
    //         let res = await getTxs(wallet.address, i);
    //         info.splice(12 * (i + 1) - 1, 0, ...res)
    //         if (info.length !== (i + 1) * 12) {
    //             break;
    //         }
    //     }
    //     setInfoList([...info])
    //     return info;
    // }

    //将得到的60笔交易信息进行分类处理得到根据地址分类的数据
    const solveTran = async (info:any) => {

        //信息解密
        const decryptedInformation = (item:any) =>{
            try {
                let nacl = require("tweetnacl");
                //获取自己的公钥
                let getPublicKeyByte = () => {
                    let keyPair: any = keyPairFromSeed(wallet.seed);
                    let publicKey = keyPair.publicKey;
                    return convertPublicKey(publicKey);
                }
                //将字符串转成字节数组
                let decodeUTF8 = function (s: string) {
                    var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
                    for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
                    return b;
                };
                //将字节数组转成字符串
                let encodeUTF8 = function (arr: any) {
                    var i, s = [];
                    for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
                    return decodeURIComponent(escape(s.join('')));
                };
                //设置随机nonce值
                nacl.setPRNG((x: any, n: any) => {
                    x = hex2Bytes_Random(n);
                })
                // 随机nonce值
                let nonceRandom = nacl.randomBytes(24);
                let DHKeyMy:any = convertKeyPair(keyPairFromSeed(wallet.seed));

                //获取他的公钥
                let data = JSON.parse(item.remarks);
                // let data :any = null;
                // console.log(`得到的数据data:${item.remarks}`)
                let pubHex:string;
                if(item.addressIn === wallet.address) //我发的消息，我将他的公钥用自己的私钥加密保存起来后面用
                {
                    var key  = Cp.enc.Utf8.parse(wallet.seed);
                    var decrypt = Cp.AES.decrypt(data.publicKey, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                    pubHex = Cp.enc.Utf8.stringify(decrypt).toString();
                    // console.log(`解析出来的数据：${pubHex}`)
                }
                else//他发的消息，我直接从签名那边获取他的公钥后面用
                {
                    let signRes = Cp.enc.Base64.parse(item.sign);
                    pubHex = signRes.toString().slice(-64);
                }
                let pub = hex2Bytes(pubHex);
                // console.log(`解析出来的公钥数组：${pub}`)
                let pubED = convertPublicKey(pub);
                // console.log(`解析出来的解密公钥数组：${pubED}`)
                var decryptedMessage = nacl.box.open(hex2Bytes(data.msg), nonceRandom,pubED, DHKeyMy.secretKey);
                let res = encodeUTF8(decryptedMessage)
                // console.log(`最终解析出来的数据：${res}`)
                return res;
            }catch (e) {
                // console.log(e)
                return false;
            }

        }

        //获取公钥
        const getPubKey = (item:any) => {
            let data = JSON.parse(item.remarks);
            let pubHex:string;
            if(item.addressIn === wallet.address) //我发的消息，我将他的公钥用自己的私钥加密保存起来后面用
            {
                var key  = Cp.enc.Utf8.parse(wallet.seed);
                var decrypt = Cp.AES.decrypt(data.publicKey, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                pubHex = Cp.enc.Utf8.stringify(decrypt).toString();
                // console.log(`解析出来的数据：${pubHex}`)
            }
            else//他发的消息，我直接从签名那边获取他的公钥后面用
            {
                let signRes = Cp.enc.Base64.parse(item.sign);
                pubHex = signRes.toString().slice(-64);
            }
            return pubHex;
        }

        var ChatListTemp = [];

        for (let i = 0; i < info.length; i++)
        {
            await sleep(0)

            try {
                // console.log(typeof info[i].remarks)
                let remarks = JSON.parse(info[i].remarks);
                if (remarks.type !== "chat") {
                    // console.log(`try里面的continue`)

                    continue;
                }
                let remarksMsgStr = decryptedInformation(info[i]);
                if(!remarksMsgStr)
                {

                    continue;
                }
                // console.log(`remarksMsgStr:${remarksMsgStr}`)
                info[i].pubkey = getPubKey(info[i]);
                info[i].remarks = JSON.stringify({height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,type:"chat",msg:remarksMsgStr,desc:""});
            }
            catch (e) {
                // console.log(`catch里面的continue`)

                continue;
            }
            // console.log(`这个显示了就不该显示continue了`);

            //本来为空就应该直接放数据进去
            if (ChatListTemp.length === 0) {
                let remarks = JSON.parse(info[i].remarks);
                let addressOut = (info[i].addressIn === wallet.address ? info[i].addressOut : info[i].addressIn);

                ChatListTemp.push({
                    pubkey:info[i].pubkey,
                    desc: addressOut.slice(0,5)+"..."+addressOut.slice(-5),
                    addressOut: addressOut,
                    info: [{height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,sender: info[i].addressIn, msg: remarks.msg, timeStamp: info[i].timestamp}]
                });

                continue;
            }
            //有数据考虑是添加数据还是新的朋友

            for (let ii = 0; ii < ChatListTemp.length; ii++) {
                await sleep(0)
                let remarks = JSON.parse(info[i].remarks);
                if (info[i].addressOut === ChatListTemp[ii].addressOut || info[i].addressIn === ChatListTemp[ii].addressOut) {
                    //后面添加信息
                    ChatListTemp[ii].info.splice(0, 0, {
                        height:info[i].height,
                        receiver:info[i].addressOut,
                        hash:info[i].hash,
                        sender: info[i].addressIn,
                        msg: remarks.msg,
                        timeStamp: info[i].timestamp
                    });
                    break;
                }
                //如果是新的朋友
                if (ii === (ChatListTemp.length - 1)) {
                    let addressOut = (info[i].addressIn === wallet.address ? info[i].addressOut : info[i].addressIn);
                    ChatListTemp.push({
                        pubkey:info[i].pubkey,
                        desc: addressOut.slice(0,5)+"..."+addressOut.slice(-5),
                        addressOut: addressOut,
                        info: [{height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,sender: info[i].addressIn, msg: remarks.msg, timeStamp: info[i].timestamp}]
                    });
                    break;
                }

            }
        }
        return ChatListTemp;
    }

    //设置名称
    const setListName = async (List: any) => {
        for (let i = 0; i < List.length; i++) {
            let addressOut = List[i].addressOut;

            let res = await SaveMyID(addressOut, "", "1");
            let Name = res.dict.nickname || addressOut.slice(0,5)+"..."+addressOut.slice(-5);
            List[i].desc = Name;
        }
        return List;
    }

    //将分类好的数据写入数据库和渲染
    const saveMsg = async (ChatListTemp: any) => {
        let maxInfoLength = constansts.ChatInfoMaxLength ;

        var resList = await getStore();//先获取数据库数据
        // console.log(`resList:${JSON.stringify(resList)}`)
        // console.log(`ChatListTemp:${JSON.stringify(ChatListTemp)}`)
        for (let i = 0; i < ChatListTemp.length; i++) {
            await sleep(0)
            //console.log(`i=${i}`)
            //数据库数据为空直接添加
            if (resList.length === 0) {
                resList.push(ChatListTemp[i]);
                for(let iii = 0 ; iii < ChatListTemp[i].info.length ; iii++ )
                {
                    // console.log(`出现错误的数据${i}   ${iii}   ${JSON.stringify(ChatListTemp[i].info[iii])}`)
                    if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                        resList[0].unread = (resList[0].unread || 0) + 1;
                    }
                }
                continue;
            }
            for (let ii = 0; ii < resList.length; ii++) {
                await sleep(0)

                //如果好友位里面已经有了，就可以比较数据进行添加了
                if (ChatListTemp[i].addressOut === resList[ii].addressOut) {
                    //添加数据
                    for (let iii = 0; iii < ChatListTemp[i].info.length; iii++) {
                        //console.log(`交易列表的时间戳${parseInt(ChatListTemp[i].info[iii].timeStamp)}`)

                        for (let j = 0; j < resList[ii].info.length; j++) {
                            await sleep(0)
                            //插入第一个
                            if(parseInt(ChatListTemp[i].info[iii].timeStamp) < resList[ii].info[0].timeStamp && j===0 && maxInfoLength > resList[ii].info.length)
                            {
                                resList[ii].show = true;
                                if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                                    resList[ii].unread = (resList[ii].unread || 0) + 1;
                                }
                                resList[ii].info.splice(0, 0, ChatListTemp[i].info[iii]);
                                break;
                            }
                            //中间相同的替换状态
                            if(parseInt(ChatListTemp[i].info[iii].timeStamp) == resList[ii].info[j].timeStamp)
                            {
                                resList[ii].info[j].showFalse = false ;
                                resList[ii].info[j].showTraning = false ;
                                resList[ii].info[j].height = ChatListTemp[i].info[iii].height;
                                break;
                            }
                            //插入中间或者最后
                            //console.log(`ChatListTemp[i].info[iii]${JSON.stringify(ChatListTemp[i].info[iii])}`)
                            if (parseInt(ChatListTemp[i].info[iii].timeStamp) > resList[ii].info[j].timeStamp && (j == (resList[ii].info.length - 1) || parseInt(ChatListTemp[i].info[iii].timeStamp) < resList[ii].info[j + 1].timeStamp)) {
                                let k = j + 1 ;
                                if(resList[ii].info.length >= maxInfoLength)
                                {
                                    resList[ii].info.shift();
                                    k--;
                                }

                                resList[ii].show = true;
                                if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                                    resList[ii].unread = (resList[ii].unread || 0) + 1;
                                }
                                resList[ii].info.splice(k, 0, ChatListTemp[i].info[iii]);
                                break;
                            }
                        }
                    }
                    break;
                }
                //新的好友位
                if (ii === (resList.length - 1)) {
                    resList.splice(0, 0, ChatListTemp[i]);

                    for(let iii = 0 ; iii < ChatListTemp[i].info.length ; iii++ )
                    {

                        if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                            resList[0].unread = (resList[0].unread || 0) + 1;
                        }
                    }
                    break;
                }
            }

            if(showWaiting)
            {
                let pL = 0.9+(i/ChatListTemp.length)*0.1;
                setProgressLength( (Math.floor(pL * 100) / 100).toString())
            }

        }

        for (let i = 0; i < resList.length; i++) {
            for(let j = 0 ; j < resList[i].info.length ; j++)
            {
                let data = resList[i].info[j];
                if(data.showTraning && ((new Date().getTime())-data.timeStamp)>(2*60*1000) && data.display!==false)
                {
                    let HashInfo = await getTxInfo(data.hash);
                    if (data.falseTime == 0 && (HashInfo == false || HashInfo.height == 0))
                    {
                        data.showFalse = true ;
                        data.showTraning = false ;
                        data.height = -2;
                    }
                    data.falseTime -= 1;
                    if(HashInfo.height > 0)
                    {
                        data.showFalse = false;
                        data.showTraning = false;
                        data.height = HashInfo.height;
                    }
                }
                resList[i].info[j] = data;
            }
        }
        resList = await setListName(resList);
        await AsyncStorage.setItem("@chatList", JSON.stringify(resList));


        setProgressLength("1");
        let timetemp = new Date().getTime()
        setChatList([...resList]);

        return resList;
    }

    //设置标题
    const setTitle = () => {
        let title = locale._("MeChat_ChatList_Title");
        navigation.setOptions({title: title})
    }

    //初始化数据
    useEffect(()=>{
        setTitle();
        //获取存储的列表，先显示出来
        getStore().then(
            async () => {
                await workHistory_First();
            }
        );
    },[])

    //初始化扫码按钮
    useEffect(() => {
        navigation.setOptions({
            headerRight: () => (
                <TouchableOpacity style={{
                    width: 30,
                    height: 35,
                    marginRight: 20,
                    alignItems: "center",
                    justifyContent: "center"
                }}
                                  onPress={ () => {
                                      navigation.navigate("ChatQRscan")
                                  }}
                >
                    <ImageBackground source={scan} style={{width: 25, height: 25}}/>
                </TouchableOpacity>
            ),
        });
    },[])

    //定时器获取数据
    useFocusEffect(
        React.useCallback(() => {
            getStore()
            workHistoryWithoutGifInterval()
            return ()=>{
            }
        }, [])
    );

    const getHistory_Random = async () => {
        var info: any = [];
        //获取最多200笔交易的信息
        let LastTime: number;
        try {
            let LastStr = await AsyncStorage.getItem("LastGetTime")  ;
            if(!LastStr)
            {
                LastStr = "1";
            }
            LastTime = parseInt( LastStr ,10) - 1 ;
            if(new Date().getTime() - LastTime > constansts.chatSearchMaxTime)
            {
                LastTime = new Date().getTime() - constansts.chatSearchMaxTime;
            }
        }catch (e) {

            LastTime = new Date().getTime() - constansts.chatSearchMaxTime;
        }

        for (let i = 0; i < Math.floor(constansts.chatSearchMaxLength/12); i++) {
            let res = [];
            try{
                res = await getTxs(wallet.address, i);
            }catch (e) {

            }
            info.splice(12 * (i + 1) - 1, 0, ...res);

            let nowGetTime = 0;
            try {
                nowGetTime = parseInt(res[res.length - 1].timestamp);
            }catch (e) {

            }
            if (info.length !== (i + 1) * 12 || nowGetTime <= LastTime) {
                break;
            }
        }
        await AsyncStorage.setItem("LastGetTime",info.length>0?info[0].timestamp.toString():LastTime.toString());
        return info;
    }

    const getHistory_First = async () => {
        var info: any = [];
        //获取最多200笔或者1星期之内的交易的信息
        let LastTime: number;
        setProgressLength("0" );
        setTipInfo(locale._("MeChat_ChatList_Tip1"))
        try {
            let LastStr = await AsyncStorage.getItem("LastGetTime") || "1" ;

            LastTime = parseInt( LastStr ) - 1 ;
            if(new Date().getTime() - LastTime > constansts.chatSearchMaxTime)
            {
                LastTime = new Date().getTime() - constansts.chatSearchMaxTime ;
            }
        }catch (e) {

            LastTime = new Date().getTime() - constansts.chatSearchMaxTime;
        }

        for (let i = 0; i < Math.floor(constansts.chatSearchMaxLength/12); i++) {
            let res = [];
            try{
                res = await getTxs(wallet.address, i);
            }catch (e) {

            }
            info.splice(12 * (i + 1) - 1, 0, ...res);
            let pL = parseFloat(progressLength);
            try {
                pL = (constansts.chatSearchMaxTime - (res[res.length - 1].timestamp - LastTime)) / constansts.chatSearchMaxTime*0.8;
            }catch (e) {

            }
            setProgressLength(pL>0.8?"0.8":pL.toString() );
            let nowGetTime = 0;
            try {
                nowGetTime = parseInt(res[res.length - 1].timestamp);
            }catch (e) {
            }
            if (info.length !== (i + 1) * 12 || nowGetTime <= LastTime) {
                setProgressLength("0.8");
                setTipInfo(locale._("MeChat_ChatList_Tip2"))
                break;
            }
        }
        await AsyncStorage.setItem("LastGetTime",info.length>0?info[0].timestamp.toString():LastTime.toString());
        return info;
    }

    const solveTran_First = async (info:any) => {

        const doSetpL = async (i: any, info: any) => {
            await sleep(1)
            let pL = 0.8 + (i / info.length) * 0.1;
            let pLM = Math.floor(pL * 100) / 100;

            setProgressLength(pLM.toString());

        }

        //信息解密
        const decryptedInformation = (item:any) =>{
            try {
                let nacl = require("tweetnacl");
                //获取自己的公钥
                let getPublicKeyByte = () => {
                    let keyPair: any = keyPairFromSeed(wallet.seed);
                    let publicKey = keyPair.publicKey;
                    return convertPublicKey(publicKey);
                }
                //将字符串转成字节数组
                let decodeUTF8 = function (s: string) {
                    var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
                    for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
                    return b;
                };
                //将字节数组转成字符串
                let encodeUTF8 = function (arr: any) {
                    var i, s = [];
                    for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
                    return decodeURIComponent(escape(s.join('')));
                };
                //设置随机nonce值
                nacl.setPRNG((x: any, n: any) => {
                    x = hex2Bytes_Random(n);
                })
                // 随机nonce值
                let nonceRandom = nacl.randomBytes(24);
                let DHKeyMy:any = convertKeyPair(keyPairFromSeed(wallet.seed));

                //获取他的公钥
                let data = JSON.parse(item.remarks);
                // let data :any = null;

                let pubHex:string;
                if(item.addressIn === wallet.address) //我发的消息，我将他的公钥用自己的私钥加密保存起来后面用
                {
                    var key  = Cp.enc.Utf8.parse(wallet.seed);
                    var decrypt = Cp.AES.decrypt(data.publicKey, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                    pubHex = Cp.enc.Utf8.stringify(decrypt).toString();

                }
                else//他发的消息，我直接从签名那边获取他的公钥后面用
                {
                    let signRes = Cp.enc.Base64.parse(item.sign);
                    pubHex = signRes.toString().slice(-64);
                }
                let pub = hex2Bytes(pubHex);

                let pubED = convertPublicKey(pub);

                var decryptedMessage = nacl.box.open(hex2Bytes(data.msg), nonceRandom,pubED, DHKeyMy.secretKey);
                let res = encodeUTF8(decryptedMessage)

                return res;
            }catch (e) {

                return false;
            }

        }

        //获取公钥
        const getPubKey = (item:any) => {
            let data = JSON.parse(item.remarks);
            let pubHex:string;
            if(item.addressIn === wallet.address) //我发的消息，我将他的公钥用自己的私钥加密保存起来后面用
            {
                var key  = Cp.enc.Utf8.parse(wallet.seed);
                var decrypt = Cp.AES.decrypt(data.publicKey, key, {mode:Cp.mode.ECB,padding: Cp.pad.Pkcs7});
                pubHex = Cp.enc.Utf8.stringify(decrypt).toString();

            }
            else//他发的消息，我直接从签名那边获取他的公钥后面用
            {
                let signRes = Cp.enc.Base64.parse(item.sign);
                pubHex = signRes.toString().slice(-64);
            }
            return pubHex;
        }

        var ChatListTemp = [];
        setTipInfo(locale._("MeChat_ChatList_Tip2"))
        for (let i = 0; i < info.length; i++)
        {
            await sleep(0)

            await doSetpL(i,info);
            try {
                // console.log(typeof info[i].remarks)
                let remarks = JSON.parse(info[i].remarks);
                if (remarks.type !== "chat") {
                    // console.log(`try里面的continue`)

                    continue;
                }
                let remarksMsgStr = decryptedInformation(info[i]);
                if(!remarksMsgStr)
                {

                    continue;
                }
                // console.log(`remarksMsgStr:${remarksMsgStr}`)
                info[i].pubkey = getPubKey(info[i]);
                info[i].remarks = JSON.stringify({height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,type:"chat",msg:remarksMsgStr,desc:""});
            }
            catch (e) {
                // console.log(`catch里面的continue`)

                continue;
            }


            //本来为空就应该直接放数据进去
            if (ChatListTemp.length === 0) {
                let remarks = JSON.parse(info[i].remarks);
                let addressOut = (info[i].addressIn === wallet.address ? info[i].addressOut : info[i].addressIn);

                ChatListTemp.push({
                    pubkey:info[i].pubkey,
                    desc: addressOut.slice(0,5)+"..."+addressOut.slice(-5),
                    addressOut: addressOut,
                    info: [{height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,sender: info[i].addressIn, msg: remarks.msg, timeStamp: info[i].timestamp}]
                });

                continue;
            }
            //有数据考虑是添加数据还是新的朋友

            for (let ii = 0; ii < ChatListTemp.length; ii++) {
                await sleep(0)
                let remarks = JSON.parse(info[i].remarks);
                if (info[i].addressOut === ChatListTemp[ii].addressOut || info[i].addressIn === ChatListTemp[ii].addressOut) {
                    //后面添加信息
                    ChatListTemp[ii].info.splice(0, 0, {
                        height:info[i].height,
                        receiver:info[i].addressOut,
                        hash:info[i].hash,
                        sender: info[i].addressIn,
                        msg: remarks.msg,
                        timeStamp: info[i].timestamp
                    });
                    break;
                }
                //如果是新的朋友
                if (ii === (ChatListTemp.length - 1)) {
                    let addressOut = (info[i].addressIn === wallet.address ? info[i].addressOut : info[i].addressIn);
                    ChatListTemp.push({
                        pubkey:info[i].pubkey,
                        desc: addressOut.slice(0,5)+"..."+addressOut.slice(-5),
                        addressOut: addressOut,
                        info: [{height:info[i].height,receiver:info[i].addressOut,hash:info[i].hash,sender: info[i].addressIn, msg: remarks.msg, timeStamp: info[i].timestamp}]
                    });
                    break;
                }

            }


        }
        return ChatListTemp;
    }

    const saveMsg_First = async (ChatListTemp: any) => {
        let maxInfoLength = constansts.ChatInfoMaxLength ;

        const doSetpL = async (i: any, info: any) => {
            await sleep(1)
            let pL = 0.9 + (i / info.length) * 0.1;
            let pLM = Math.floor(pL * 100) / 100;

            setProgressLength(pLM.toString());

        }

        var resList = await getStore();//先获取数据库数据

        for (let i = 0; i < ChatListTemp.length; i++) {
            await doSetpL(i, ChatListTemp);
            await sleep(0)
            //数据库数据为空直接添加
            if (resList.length === 0) {
                if(ChatListTemp[i].info.length > maxInfoLength)
                {
                    while(ChatListTemp[i].info.length <= maxInfoLength)
                    {
                        ChatListTemp[i].info.shift();
                    }
                }
                resList.push(ChatListTemp[i]);
                for(let iii = 0 ; iii < ChatListTemp[i].info.length ; iii++ )
                {

                    if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                        resList[0].unread = (resList[0].unread || 0) + 1;
                    }
                }
                continue;
            }
            for (let ii = 0; ii < resList.length; ii++) {
                await sleep(0)

                if (ChatListTemp[i].addressOut === resList[ii].addressOut) {
                    //添加数据
                    for (let iii = 0; iii < ChatListTemp[i].info.length; iii++) {
                        //console.log(`交易列表的时间戳${parseInt(ChatListTemp[i].info[iii].timeStamp)}`)

                        for (let j = 0; j < resList[ii].info.length; j++) {
                            await sleep(0)
                            if(parseInt(ChatListTemp[i].info[iii].timeStamp) < resList[ii].info[0].timeStamp && j===0 && resList[ii].info.length < maxInfoLength)
                            {
                                resList[ii].show = true;
                                if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                                    resList[ii].unread = (resList[ii].unread || 0) + 1;
                                }
                                resList[ii].info.splice(0, 0, ChatListTemp[i].info[iii]);
                                break;
                            }
                            if(parseInt(ChatListTemp[i].info[iii].timeStamp) == resList[ii].info[j].timeStamp)
                            {
                                resList[ii].info[j].showFalse = false ;
                                resList[ii].info[j].showTraning = false ;
                                resList[ii].info[j].height = ChatListTemp[i].info[iii].height;
                                break;
                            }
                            //console.log(`ChatListTemp[i].info[iii]${JSON.stringify(ChatListTemp[i].info[iii])}`)
                            if (parseInt(ChatListTemp[i].info[iii].timeStamp) > resList[ii].info[j].timeStamp && (j == (resList[ii].info.length - 1) || parseInt(ChatListTemp[i].info[iii].timeStamp) < resList[ii].info[j + 1].timeStamp)) {
                                let k = j+1;
                                if(resList[ii].info.length >= maxInfoLength)
                                {
                                    resList[ii].info.shift();
                                    k--;
                                }
                                resList[ii].show = true;
                                if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                                    resList[ii].unread = (resList[ii].unread || 0) + 1;
                                }
                                resList[ii].info.splice(k, 0, ChatListTemp[i].info[iii]);
                                break;
                            }
                        }
                    }
                    break;
                }
                //新的好友位
                if (ii === (resList.length - 1)) {
                    resList.splice(0, 0, ChatListTemp[i]);

                    for(let iii = 0 ; iii < ChatListTemp[i].info.length ; iii++ )
                    {

                        if (ChatListTemp[i].info[iii].sender !== wallet.address) {
                            resList[0].unread = (resList[0].unread || 0) + 1;
                        }
                    }
                    break;
                }
            }

            if(showWaiting)
            {
                let pL = 0.9+(i/ChatListTemp.length)*0.1;
                setProgressLength( (Math.floor(pL * 100) / 100).toString())
            }

        }

        for (let i = 0; i < resList.length; i++) {
            for(let j = 0 ; j < resList[i].info.length ; j++)
            {
                let data = resList[i].info[j];
                if(data.showTraning && ((new Date().getTime())-data.timeStamp)>(2*60*1000) && data.display!==false)
                {
                    let HashInfo = await getTxInfo(data.hash);
                    if (data.falseTime == 0 && (HashInfo == false || HashInfo.height == 0))
                    {
                        data.showFalse = true ;
                        data.showTraning = false ;
                        data.height = -2 ;
                    }
                    data.falseTime -= 1;
                    if(HashInfo.height > 0)
                    {
                        data.showFalse = false;
                        data.showTraning = false;
                        data.height = HashInfo.height;
                    }
                }
                resList[i].info[j] = data;
            }
        }
        resList = await setListName(resList);
        await AsyncStorage.setItem("@chatList", JSON.stringify(resList));

        setProgressLength("1");
        // setChatList([...resList]);

        return resList;
    }

    const checkNeedUpdate = async () => {
        let beforeTransferCountStr: string | null = "0";
        try {
            beforeTransferCountStr = await AsyncStorage.getItem("Transfer_Count")
        }catch (e) {
            beforeTransferCountStr = "0";
        }

        if(beforeTransferCountStr == null || beforeTransferCountStr == "0")
        {
            let newTransferCount = await getTransferCount(wallet.address);

            await AsyncStorage.setItem("Transfer_Count",newTransferCount.count.toString());
            return true;

        }
        let beforeTransferCount = parseInt(beforeTransferCountStr);

        let newTransferCount = await getTransferCount(wallet.address);

        if(newTransferCount.count > beforeTransferCount)
        {
            await AsyncStorage.setItem("Transfer_Count",newTransferCount.count.toString());
            return true;
        }
        return false;
    }

    const sortList_First = (resList: any) => {
        const getLastTime = (List:any) => {
            if(List.length > 0)
            {
                return List[List.length - 1].timeStamp;
            }
            return 3744434681000;
        }

        function bubbleSort(arr:any) {//冒泡排序
            var len = arr.length;
            for(var i = 0; i < len - 1; i++) {
                for(var j = 0; j < len - 1 - i; j++) {
                    try {
                        let j_LastTime = getLastTime(arr[j].info);
                        let j_NextLastTime = getLastTime(arr[j+1].info);
                        if ( j_LastTime < j_NextLastTime) {       // 相邻元素两两对比
                            var temp = arr[j + 1];       // 元素交换
                            arr[j + 1] = arr[j];
                            arr[j] = temp;
                        }
                    }catch (e) {
                    }
                }
            }
            return arr;
        }
        let resultList = bubbleSort(resList);
        setChatList(resultList);
        AsyncStorage.setItem("@chatList",JSON.stringify(resultList))
    }

    const workHistory_First = async () => {
        // console.log("开始获取所有历史记录")
        setShowWaiting(true);

        //判断一下是否需要获取数据

        let NeedUpdate = await checkNeedUpdate();
        if(!NeedUpdate)
        {
            setProgressLength("1");
            setTimeout(()=>{
                setShowWaiting(false)
                setProgressLength("0");
            },300)

            if(constansts.chatCustomer)
            {
                let customInfo = {
                    pubkey:"c8f6d9f616ca23e4b6e4ee1358ea7149dba542772fbb189a8061f8f92d7baefb",
                    addressOut:"fPnu3VCHyKe4fX6ByMtyxLfMV5spfA2oN",
                    desc:"密信客服",
                    customer:true,info:[],
                    // logo:{uri:"https://wallet.smartx.one/img/logo.9a2b681a.png"},
                };

                let resList = await getStore();

                for(let i = 0 ; i < resList.length ; i++)
                {
                    if(resList[i].customer || resList[i].addressOut === "fPnu3VCHyKe4fX6ByMtyxLfMV5spfA2oN" )
                    {
                        resList[i].customer = true;
                        resList[i].show = true;
                        resList[i].pubkey = "c8f6d9f616ca23e4b6e4ee1358ea7149dba542772fbb189a8061f8f92d7baefb";
                        // resList[i].logo = {uri:"https://wallet.smartx.one/img/logo.9a2b681a.png"};
                        break;
                    }
                    if(i == (resList.length - 1))
                    {
                        resList.splice(0,0,customInfo)
                        break;
                    }
                }
                if(resList.length == 0)
                {
                    resList.push(customInfo)
                }

                await AsyncStorage.setItem("@chatList",JSON.stringify(resList))
            }
            return ;
        }

        //获取最新交易
        var info = await getHistory_First();

        //将信息分类写入
        var ChatListTemp = await solveTran_First(info);

        //将好友列表比较并且保存
        let resList = await saveMsg_First(ChatListTemp);

        sortList_First(resList);

        if(constansts.chatCustomer)
        {
            let customInfo = {
                pubkey:"c8f6d9f616ca23e4b6e4ee1358ea7149dba542772fbb189a8061f8f92d7baefb",
                addressOut:"fPnu3VCHyKe4fX6ByMtyxLfMV5spfA2oN",
                desc:"密信客服",
                customer:true,info:[],
                // logo:{uri:"https://wallet.smartx.one/img/logo.9a2b681a.png"},
            };

            let resList = await getStore();
            for(let i = 0 ; i < resList.length ; i++)
            {
                if(resList[i].customer || resList[i].addressOut === "fPnu3VCHyKe4fX6ByMtyxLfMV5spfA2oN" )
                {
                    resList[i].customer = true;
                    resList[i].show = true;
                    resList[i].pubkey = "c8f6d9f616ca23e4b6e4ee1358ea7149dba542772fbb189a8061f8f92d7baefb";
                    // resList[i].logo = {uri:"https://wallet.smartx.one/img/logo.9a2b681a.png"};
                    break;
                }
                if(i == (resList.length - 1))
                {
                    resList.splice(0,0,customInfo)
                    break;
                }
            }
            if(resList.length == 0)
            {
                resList.push(customInfo)
            }
            await AsyncStorage.setItem("@chatList",JSON.stringify(resList))
        }

        setShowWaiting(false)
        setProgressLength("0");
    }

    const workHistoryWithoutGif = async () => {
        if(showWaiting)
        {
            return ;
        }
        let NeedUpdate = await checkNeedUpdate();

        if(!NeedUpdate)
        {
            return;
        }


        //获取最新交易
        var info = await getHistory_Random();

        //将信息分类写入
        var ChatListTemp = await solveTran(info);

        //将好友列表比较并且保存
        let resList = await saveMsg(ChatListTemp);

        sortList_First(resList);
    }

    const workHistoryWithoutGifInterval = async () => {
        if(showWaiting)
        {
            setTimeout(workHistoryWithoutGifInterval,10*1000);
            return ;
        }
        let NeedUpdate = await checkNeedUpdate();

        if(!NeedUpdate)
        {
            setTimeout(workHistoryWithoutGifInterval,10*1000);
            return;
        }


        //获取最新交易
        var info = await getHistory_Random();

        //将信息分类写入
        var ChatListTemp = await solveTran(info);

        //将好友列表比较并且保存
        let resList = await saveMsg(ChatListTemp);

        sortList_First(resList);

        setTimeout(workHistoryWithoutGifInterval,10*1000);
    }

    return (
        <View>
            {
                showWaiting?
                    <View style={{width:width,height:height,backgroundColor:"#F5F5F5"}}>
                        <ActivityIndicator
                            animating={true}
                            color={'lightblue'}
                            size={50}
                            style={{width:width,backgroundColor:"#FFFAFA69",marginTop:0.3*height}}
                        />
                        <Text style={{alignSelf:"center",marginTop:20}}>{formartMoney((parseFloat(progressLength)*100).toString(),2)}% {TipInfo}</Text>
                        <View style={{backgroundColor:"#DCDCDC",width:width*0.8,height:20,borderRadius:10,marginTop:25,alignSelf:"center"}}/>
                        <View style={{backgroundColor:"#69BDF4",width:width*0.8*parseFloat(progressLength)>20?width*0.8*parseFloat(progressLength):20,height:20,borderRadius:10,marginTop:-20,alignSelf:"flex-start",marginLeft:width*0.1}}/>
                    </View>:null
            }
            <ScrollView
                style={{height:height*0.9}}
                refreshControl={
                    <RefreshControl refreshing={false} onRefresh={() => {workHistoryWithoutGif()}} collapsable={true}/>
                }>
                <View >
                    {
                        ChatList.length
                            ?
                            ChatList.map((tx: any,index:any) => (
                                tx.show!==false?
                                    <TouchableHighlight
                                              underlayColor="rgba(34, 26, 38, 0.1)"
                                              onPress={ async ()=>
                                              {

                                                  let tempList = await getStore();
                                                  tempList[index].unread = 0;

                                                  await AsyncStorage.setItem("@chatList", JSON.stringify(tempList));
                                                  let timetemp = new Date().getTime()
                                                  setChatList([...tempList]);

                                                  navigation.navigate("ChatView",{ToAddress:tx.addressOut,desc:tx.desc || (tx.addressOut.slice(0,5)+"..."+tx.addressOut.slice(-5)),pubkey:tx.pubkey,info:tx.info || []})
                                              }}
                                              onLongPress={async () => {
                                                  const delChat = async () => {
                                                      let tempList = [...ChatList];
                                                      tempList[index].show = false;
                                                      await AsyncStorage.setItem("@chatList", JSON.stringify(tempList));
                                                      setChatList([...tempList]);
                                                  }
                                                  Alert.alert('', `是否删除与 ${tx.desc || (tx.addressOut.slice(0,5)+"..."+tx.addressOut.slice(-5))} 的对话`, [{
                                                      text: locale?._('cancel'),
                                                      onPress: () => console.log("Cancel Pressed"),
                                                      style: "cancel"
                                                  }, {
                                                      text: locale?._('ok'),
                                                      onPress: async () => {
                                                          await delChat();
                                                      }}
                                                  ]);

                                              }}
                                              key={index}>
                                        <View style={{flexDirection:"row",marginTop:5,padding:10,paddingBottom:0}}>
                                            <ImageBackground source={tx.logo?{uri:tx.logo.uri}:otherTokenLogo} style={{ width: 45, height: 45 ,marginRight:15,marginTop:5}} />
                                            <ListItem.Content style={{borderBottomColor:"#F5F5F5",borderBottomWidth:1,paddingBottom:7}}>
                                                <ListItem.Title style={{fontSize:width/360*15,marginBottom:10}} numberOfLines={1}>{tx.desc}</ListItem.Title>
                                                <ListItem.Subtitle style={{height:15,fontSize:width/360*10}} numberOfLines={1}>
                                                    <Text numberOfLines={1} style={{color:'grey'}}>
                                                        {(tx.info.length - 1)>=0?(tx.info[(tx.info.length - 1)].msg):"" }
                                                    </Text>
                                                </ListItem.Subtitle>
                                            </ListItem.Content>
                                            <View style={{borderBottomColor:"#F5F5F5",paddingBottom:7,borderBottomWidth:1,width:width/360*80,flexDirection:"column",alignItems:"flex-end",marginRight:width/360*0}}>
                                            <View style={{flexDirection:"column",width:width/360*80,justifyContent:"flex-end",marginBottom:10}}>
                                                <Text style={{fontSize:width/360*12,color:"grey",alignSelf:"flex-end"}}>
                                                    {(tx.info.length - 1)>=0?(timeFormat((tx.info[(tx.info.length - 1)].timeStamp)).slice(5,16)):"" }
                                                </Text>
                                            </View>
                                            <View style={{flexDirection:"column",width:width/360*50,justifyContent:"center"}}>
                                                {
                                                    tx.unread?
                                                        <Text style={{marginTop:5,fontSize:width/360*12,color:"white",alignSelf:"flex-end",backgroundColor:"lightgrey",paddingLeft:12,paddingRight:12,borderRadius:12}}>
                                                            {tx.unread || ""}
                                                        </Text>
                                                        :
                                                        <Text style={{marginTop:5,fontSize:width/360*12,color:"white",alignSelf:"flex-end"}}>
                                                            {""}
                                                        </Text>
                                                }

                                            </View>
                                        </View>
                                        {/*<Icon type='feather' name='arrow-right' color='#7259E0FF' size={24} />*/}
                                        </View>
                                    </TouchableHighlight>
                                    :null
                            ))
                            :
                            <View style={{ flex: 1, justifyContent: 'center' }}>
                                <Text style={{
                                    marginTop: '100%',
                                    fontSize: 20,
                                    textAlign: 'center',
                                    color: 'grey'
                                }}>{locale?._('noContent')}</Text>
                            </View>
                    }
                </View>
            </ScrollView>

        </View>
    );
};
export default ChatListTemp;
